package flextv.main.logic {

import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;

import flextv.core.logic.Logger;
import flextv.core.logic.Util;
import flextv.core.vo.Playlist;
import flextv.core.vo.StoredItem;
import flextv.data.IPersistenceService;
import flextv.main.logic.download.IDownloadService;

import mx.controls.Alert;
import mx.logging.ILogger;
	

public class AddItemServiceImpl implements IAddItemService {
	
	
	private static const LOG: ILogger = Logger.getLog(AddItemServiceImpl);
	
	
	public var downloadService: IDownloadService;
	
	public var persistenceService: IPersistenceService;
	
	
	public function downloadAddItem(newStoredItem: StoredItem, targetPlaylist: Playlist, thumbnailDownloadUrl: String): void {
		LOG.info("downloadAddItem(newStoredItem=["+newStoredItem+"], targetPlaylist=["+targetPlaylist+"], thumbnailDownloadUrl=["+thumbnailDownloadUrl+"])");
		
		if(thumbnailDownloadUrl == null || thumbnailDownloadUrl.length == 0) throw new ArgumentError("Invalid thumbnailDownloadUrl!");
		
		// flv video file within application-storage/videos
		const targetFlvFile: File = Util.resolveFlvFile(newStoredItem);
		
		this.downloadService.download(newStoredItem, targetFlvFile, function(): Boolean {
			
		
			// onFlvUriReady callback
			// -----------------------
			if(persistenceService.isYidAlreadyStored(newStoredItem.yid) == true) {
				Alert.show("You already have that YouTube video stored!\n" +
							"(YouTube ID: " + newStoredItem.yid + ")", "Error");
				return false; // do not start download, if video (by yid) is already stored
			}
			
			// convert DOS "\" to UNIX "/"
			newStoredItem.fileUri = "file://" + Util.resolveFlvFile(newStoredItem).nativePath.replace(/\\/,"/")
			
			
			// download thumbnail
			const targetThumbFile: File = Util.resolveThumbFile(newStoredItem);
			copyThumbnail(newStoredItem, targetThumbFile, thumbnailDownloadUrl);
			
			
			// insert into database
			persistenceService.insertStoredItem(newStoredItem, targetPlaylist);
			
			// add to proper playlist
			targetPlaylist.storedItems.addItem(newStoredItem);
			
			// invalidate UI hack
			MainModel.instance.playlistGridHack.invalidateList();
			
			return true;
		});
	}
	
	private static function copyThumbnail(newStoredItem: StoredItem, targetFile: File, downloadUrl: String): void {
		LOG.info("copyThumbnail(targetFile=["+targetFile.nativePath+"]; downloadUrl=["+downloadUrl+"])");
		// copyThumbnail(targetFile=[/Users/xxx/Library/Preferences/flextv.FlexTV/Local Store/thumbnails/Xfbyb1cOK94.png]; downloadUrl=[http://i.ytimg.com/vi/Xfbyb1cOK94/2.jpg])
		
		// http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_7.html
		const request: URLRequest = new URLRequest(downloadUrl);
		const stream: URLStream = new URLStream();
		stream.load(request);
		stream.addEventListener(Event.COMPLETE, function(event: Event): void {
			LOG.debug("Finished downloading thumbnail from ["+downloadUrl+"]");
			var fileData: ByteArray = new ByteArray();
			stream.readBytes(fileData, 0, stream.bytesAvailable);
	
			var fileStream: FileStream = new FileStream();
			fileStream.open(targetFile, FileMode.WRITE);
			fileStream.writeBytes(fileData, 0, fileData.length);
			fileStream.close();
			
			// update thumbnail path
			newStoredItem.thumbnailUrl = "file://" + targetFile.nativePath.replace(/\\/,"/");
		});
	}

	// singleton stuff
	private static var INSTANCE: AddItemServiceImpl; 
	public function AddItemServiceImpl(singletonEnforcer: SingletonEnforcer) { }
	
	public static function getInstance(): AddItemServiceImpl {
		if(INSTANCE == null) { INSTANCE = new AddItemServiceImpl(new SingletonEnforcer()); }
		return INSTANCE;
	}
}
}

class SingletonEnforcer { }